package com.koron.css2.common.service;

import com.koron.css2.ExportExcelInterface;
import com.koron.css2.common.dto.AttachmentDto;
import com.koron.css2.common.utils.ExcelUtils;
import com.koron.css2.common.utils.TxtUtils;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.DBSourceUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.SqlTask;
import org.springframework.http.HttpEntity;

import java.util.Objects;

public abstract class AbstractExportExcel implements ExportExcelInterface{
	
	public abstract AttachmentDto getAttachment(SessionFactory factory, UserInfoBean userInfo, RequestBean req);
	
	public HttpEntity<?> exportExcel(UserInfoBean userInfo, RequestBean req){
		AttachmentDto attachment = null;
		try {
			attachment = ADOConnection.runTask(DBSourceUtils.getDbEnv(userInfo.getCurWaterCode()), 
			new SqlTask() {
				@Override
				public Object run(SessionFactory factory) {
					return getAttachment(factory, userInfo, req);
				}
			}, AttachmentDto.class);
		} catch (Exception e) {
			throw new RuntimeException("获取导出附件数据出错!!!", e);
		}
		if(attachment == null) {
			throw new IllegalArgumentException("导出附件数据不能为空!!!");
		}
		HttpEntity<?> httpEntity = null;
		if(Objects.equals("txt", attachment.getFileType())) {  // 导出txt
			httpEntity = TxtUtils.exportTxt(attachment.getData(), attachment.getTitle(), attachment.getFilename());
		} else if (Objects.equals("excel", attachment.getFileType())) {  //导出excel
			httpEntity = ExcelUtils.exportExcel(attachment.getData(), attachment.getFilename(), attachment.getFileTemplate(), attachment.getBtlTemplate());
		} else {
			throw new IllegalArgumentException("未知的的附件类型：" + attachment.getFileType());
		}
		return httpEntity;
	}
}
